const express = require('express');
const app = express();

app.use(express.json());

let posts = []; // 存储帖子数据

// 获取帖子列表
app.get('/getPosts', (req, res) => {
  res.send(posts);
});

// 添加帖子
app.post('/addPost', (req, res) => {
  const post = req.body;
  post.id = Date.now();
  posts.push(post);
  res.send({ code: 0, message: '添加成功' });
});

// 删除帖子
app.post('/deletePost', (req, res) => {
  const { id } = req.body;
  const index = posts.findIndex(post => post.id == id);
  if (index !== -1) {
    posts.splice(index, 1);
    res.send({ code: 0, message: '删除成功' });
  } else {
    res.status(404).send({ code: 1, message: '帖子不存在' });
  }
});

// 更新帖子
app.post('/updatePost', (req, res) => {
  const post = req.body;
  const index = posts.findIndex(p => p.id == post.id);
  if (index !== -1) {
    posts[index] = post;
    res.send({ code: 0, message: '更新成功' });
  } else {
    res.status(404).send({ code: 1, message: '帖子不存在' });
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
